package org.ceasaro.epistor.web.provide;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping(value = "/provide")
public class ProvideController {

   public static final Logger log = LoggerFactory.getLogger(ProvideController.class);

   @RequestMapping(method = RequestMethod.GET)
   public String initialCreate(Model model) {
      model.addAttribute(new Provide());
      return "provide/initialCreate";
   }

   @RequestMapping(method=RequestMethod.POST)
   public String create(@Valid Provide provide, BindingResult result, Model model) {
      if (result.hasErrors()) {
         return "provide/initialCreate";
      }
      StringTokenizer tokenizer = new StringTokenizer(provide.getCharacteristic(), ",");
      Map<String, String> characteristics = new HashMap<String, String>();
      while (tokenizer.hasMoreTokens() )
      {
         String characteristic = tokenizer.nextToken();
         int indexOfEqual = characteristic.indexOf('=');
         characteristics.put(characteristic.substring(0, indexOfEqual), characteristic.substring(indexOfEqual+1));
      }
      model.addAttribute("foundCharacteristics", characteristics);
      return "provide/initialCreate";
   }

}